/*
 * Copyright (c) 2016-2017 fulihui.com All right reserved
 * Project: integral-business-parent
 * File name: ZbusIntegralCreator.java
 */

package com.fulihui.integralbusiness.producer;

import com.alibaba.fastjson.JSON;
import com.fulihui.integralbusiness.constants.IntegralBusinessConstants;
import com.fulihui.integralbusiness.constants.IntegralBusinessFlags;
import org.zbus.broker.Broker;
import org.zbus.broker.ZbusBroker;
import org.zbus.mq.Producer;
import org.zbus.net.http.Message;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Willard.Hu on 2017/4/21 0021.
 */
public class ZbusIntegralCreator {
    private Map<IntegralBusinessFlags, Producer> producers = new ConcurrentHashMap<>();
    private Broker                               broker;

    public void create(IntegralBusinessFlags flag, Map<String, Object> msg) throws IOException {
        Producer producer = producers.computeIfAbsent(flag, f ->
                new Producer(broker,
            IntegralBusinessConstants.ZBUS_MQ_NAME_PREFIX + f.name()));
        Message message = new Message(JSON.toJSONString(msg));
        producer.sendAsync(message);
    }

    public void setAddress(String address) {
        try {
            this.broker = new ZbusBroker(address);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
